﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PayrollHR.Web;
using Payroll.Common.Utils;
using Payroll.BusinessLogic;
using Payroll.BusinessLogic.Directory;
using Payroll.BusinessLogic.CustomerManager;
using Payroll.BusinessLogic.Utils;
using MigraDoc.DocumentObjectModel;
using Payroll.BusinessLogic.Devices;
using Payroll.BusinessLogic.Package;
using System.IO;
using OfficeOpenXml;
using System.Collections.Generic;

namespace PayrollHR.Administration.Modules
{
    public partial class VoucherImportControl : BasePayrollAdministrationUserControl
    {
        public int VoucherID
        {
            get
            {
                return CommonHelper.QueryStringInt("VoucherID");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.FillDropDowns();
            }
        }
        public void FillDropDowns(string vendor = null, int? OwnerId = null, int? PackagesID = null)
        {
            this.FillOwerDropDowns(OwnerId);
        }
        public void FillOwerDropDowns(int? OwnerId = null, int? customerid = null)
        {
            ddlOwner.Items.Clear();
            var owerColection = this.CustomerService.GetAllCustomer();
            owerColection.Insert(0, new Customer { CustomerId = 0, CustName = "----Chọn đơn vị----" });
            foreach (var customer in owerColection)
            {
                ListItem ddlCustTypeItem2 = new ListItem(customer.CustName, customer.CustomerId.ToString());
                ddlOwner.Items.Add(ddlCustTypeItem2);
                ddlCustomer.Items.Add(ddlCustTypeItem2);
            }
            if (OwnerId.HasValue)
            {
                ddlOwner.SelectedValue = CommonHelper.ToString(OwnerId);
            }
            if (customerid.HasValue)
            {
                ddlCustomer.SelectedValue = CommonHelper.ToString(customerid);
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (ImportFileUpload.HasFile)
            {
                string file_name = "";
                string path = "~/Files/UploadFile/";
                if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    System.IO.Directory.CreateDirectory(Server.MapPath(path));
                else
                {
                    file_name = CommonHelper.ToString(PayrollContext.Current.Session.EmployeeId) + ImportFileUpload.FileName;
                    file_name = Server.MapPath(path) + System.IO.Path.GetFileName(file_name);
                    if (File.Exists(file_name))
                    {
                        File.Delete(file_name);
                    }
                    ImportFileUpload.SaveAs(file_name);
                    var existingFile = new FileInfo(file_name);

                    using (var package = new ExcelPackage(existingFile))
                    {
                        ExcelWorkbook workBook = package.Workbook;
                        if (workBook != null && workBook.Worksheets.Count > 0)
                        {
                            ExcelWorksheet currentWorksheet = workBook.Worksheets[1];
                            this.ImportExcell(currentWorksheet);
                        }
                    }
                    File.Delete(existingFile.FullName);
                }
            }
        }
        #region Function        
        private void ImportExcell(ExcelWorksheet sheetData)
        {
            int OwnerId = CommonHelper.ToInteger(ddlOwner.SelectedItem.Value);
            int CustomerId = CommonHelper.ToInteger(ddlCustomer.SelectedItem.Value);
            int rowCount = sheetData.Dimension.End.Row;
            List<Voucher> List = new List<Voucher>();
            var packetColection = this.PackageService.GetAllPackage();
            int PacketId = 0;
            string taxcode = "";
            string companyName = "";
            string address = "";
            string PacketCode = "";
            string Vendor = "";
            string note = "";
            string Transdate = "";
            int User = PayrollContext.Current.Session.EmployeeId;
            for (int i = 3; i <= rowCount; i++)
            {
                taxcode = CommonHelper.ToString(sheetData.Cells[i, 2].Value);
                companyName = CommonHelper.ToString(sheetData.Cells[i, 3].Value);
                address = CommonHelper.ToString(sheetData.Cells[i, 4].Value);
                PacketCode = CommonHelper.ToString(sheetData.Cells[i, 5].Value);
                Vendor = CommonHelper.ToString(sheetData.Cells[i, 7].Value);
                note = CommonHelper.ToString(sheetData.Cells[i, 11].Value);
                PacketId = this.GetPacketId(packetColection, PacketCode.ToUpper());
                Transdate = CommonHelper.ToString(sheetData.Cells[i, 12].Value);
                if (Transdate.Length == 0)
                    continue;
                if (CommonHelper.IsNull(CommonHelper.ToDate(Transdate)))
                    continue;
                Transdate = CommonHelper.ToDate(Transdate).Value.ToString("yyyy-MM-dd");

                if (taxcode.Length > 0 && companyName.Length > 0 && PacketId > 0 && Vendor.Length > 0)
                {
                    List.Add(new Voucher
                    {
                        Transdate = Transdate,
                        CustomerId = CustomerId,
                        Taxcode = taxcode,
                        CompanyName = companyName,
                        Address = address,
                        PacketId = PacketId,
                        OwnerId = OwnerId,
                        Vendor = Vendor,
                        Note = note,
                        Createby = User,
                        Modified = User
                    });
                }
            }
            if (List.Count > 0)
            {
                VoucherService.Save(List);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="List"></param>
        /// <param name="PacketCode"></param>
        /// <returns></returns>
        private int GetPacketId(List<Package> List, string PacketCode)
        {
            Package result = List.Find(
            delegate(Package p)
            {
                return p.PackCode.ToUpper() == PacketCode;
            });
            return CommonHelper.IsNull(result) ? 0 : result.PackagesID;           
        }
        #endregion
    }
}